package hhq.demo.ctrl;

import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import hhq.demo.mapper.RandomMapper;
import hhq.demo.pojo.Room;
import hhq.demo.utils.ResJson;

/**
 * 随机数的后端接口，思想： 创建一个房间room，里面添加若干user，每个user输入一个数number作为种子seek，
 * 当半数的user都输入自己的种子之后，将输入的所有seek拼接形成seeks， 将seeks作为java随机函数的随机种子，然后取 用户数
 * 个整数，对应每个user， 从小到大排序，输出user排序序列
 *
 * 表设计：
CREATE TABLE IF NOT EXISTS `tb_random` (
  `roomid` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `roomname` TEXT,
  `roomusers` TEXT,
  `roomnumbers` TEXT,
  `result` TEXT,
  `resultusers` TEXT
);

 */
@RestController
@RequestMapping( "/random")
public class RandomController {

    @Resource
    RandomMapper randomMapper;

    //创建房间
    @RequestMapping(value = "/createRoom", method = RequestMethod.GET) // ?roomname=myname&roomusers=霍华骑,林则徐
    public String createRoom(
        @RequestParam(name = "roomname") String roomname,
            @RequestParam(name = "roomusers") String roomusers

    ) {
        if(roomname==null || roomusers==null ||
            roomname.equals("") || roomusers.equals("") ){
            return ResJson.getString(40, "不能为空，创建room失败");
        }
        Room room = new Room();
        room.setRoomname(roomname);
        room.setRoomusers(roomusers);
        randomMapper.insertRoom(room);
        List<Room> l = randomMapper.getAllRooms(); //返回最新的room，即刚刚创建的
        return ResJson.getString(20, "创建room成功", l.get(l.size()-1));
    }

    // 新增一个数  未生成结果
    @RequestMapping(value = "/addOneNumber", method = RequestMethod.GET) //
    public String addOneNumber(@RequestParam(name = "roomid") String roomid,
            @RequestParam(name = "number") String number) {

        Room room = randomMapper.getOneRoom(Integer.parseInt(roomid));
        // System.out.println("get result:" + room.getResult());
        if(room.getResult() != null && ! room.getResult().equals("") ){
            return ResJson.getString(40, "已经生成结果，无法添加新的seek");
        }
        String numbers = room.getRoomnumbers();
        if(numbers == null || numbers.equals("") ||  numbers.equals("null")){
            room.setRoomnumbers( number.trim());
        }else{
            room.setRoomnumbers(numbers + "," + number.trim());
        }

        randomMapper.updateRoom(room);
        return ResJson.getString(20, "新增number 成功", room);
    }

    @RequestMapping(value = "/generateResult", method = RequestMethod.GET) //
    public String generateResult(@RequestParam(name = "roomid") String roomid) {
        Room room = randomMapper.getOneRoom(Integer.parseInt(roomid));
        String numbers = room.getRoomnumbers();
        String users = room.getRoomusers();
        String[] numberList = numbers.split(",");
        String[] userList = users.split(",");
        //半数以上才能生成结果
        if(numbers==null|| numbers.equals("")|| numberList.length < userList.length/2.0 ){
            return ResJson.getString(40, "半数人提交seek才能生成结果");
        }

        int[] numberArr = new int[numberList.length];
        int i = 0;
        int seek = 0;
        for (String n : numberList) {
            // System.out.println(n);
            numberArr[i++] = Integer.parseInt(n);
            seek = seek   + numberArr[i - 1];
        }
        Random rand = new Random(seek);
        int[] resultList = new int[userList.length];
        String result = "";
        for (i = 0; i < userList.length; i++) {
            resultList[i] = rand.nextInt(65535);
            result += resultList[i]+ ",";
        }
        result = result.substring(0, result.length()-1);
        room.setResult(result); //存入随机数结果 形如: 452,8996,125,2,451

        // 冒泡排序
        for ( i = 0; i < resultList.length - 1; i++) {
            for (int j = 0; j < resultList.length - 1 - i; j++) {
                if (resultList[j] > resultList[j + 1]) {
                    int temp = resultList[j];
                    resultList[j] = resultList[j + 1];
                    resultList[j + 1] = temp;
                    String tmp = userList[j];
                    userList[j] = userList[j + 1];
                    userList[j + 1] = tmp;
                }
            }
        }
        String resultUsers="";
        for(String user: userList){
            resultUsers+= user+",";
        }
        resultUsers = resultUsers.substring(0, resultUsers.length()-1);
        room.setResultusers(resultUsers);

        //存入数据库
        randomMapper.updateRoom(room);

        return ResJson.getString(20, "生成结果成功", room);
    }

    @RequestMapping(value = "/getOneRoom", method = RequestMethod.GET) //
    public String getOneRoom(@RequestParam(name = "roomid") String roomid) {
        try {
            int id = Integer.parseInt(roomid);
            Room room = randomMapper.getOneRoom(id);
            return ResJson.getString(20, "获取成功", room);
        } catch (Exception e) {
            System.out.println("error to getOneRoom:"+e.toString());
        }

        return ResJson.getString(40, "传入参数不正确");
    }

    @RequestMapping(value = "/getOneRoomByName", method = RequestMethod.GET) //
    public String getOneRoomByName(@RequestParam(name = "roomname") String roomname) {
        try {
            if(roomname.charAt(0) != '%'){
                roomname = "%" + roomname;
            }
            if(roomname.charAt(roomname.length()-1) != '%'){
                roomname = roomname + "%";
            }
            Room room = randomMapper.getOneRoomByName(roomname);
            return ResJson.getString(20, "获取成功", room);
        } catch (Exception e) {
            System.out.println("error to getOneRoom:"+e.toString());
        }

        return ResJson.getString(40, "传入参数不正确");
    }

    // 获取当前的所有房间 json
    @RequestMapping(value = "/getAllRoom", method = RequestMethod.GET) //
    public String getAllRoom(  ) {

        List<Room> list = randomMapper.getAllRooms();
        return ResJson.getString(20, "获取成功", list);
    }


    // 列出html的所有房间信息
    @RequestMapping(value = "/all", method = RequestMethod.GET) //
    public String all(  ) {
        List<Room> list = randomMapper.getAllRooms();
        String res = "<h1>roomid:  -  name --  roomusers <br>";
        for(Room r: list){
            res+= r.getRoomid() + "--"+  r.getRoomname() + "--" + r.getRoomusers() +"<br>";
        }
        res+="</h1>";
        return res;
    }

}
